# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

import frappe
from frappe import _
from erpnext.accounts.report.financial_statements import (
    get_period_list,
    get_columns,
    get_data
)
from erpnext.accounts.report.profit_and_loss_statement.profit_and_loss_statement import (
    get_chart_data
)
from .financial_statements_cn import get_financial_statements_cn

def execute(filters=None):
    if not filters:
        filters = {}

    # 验证必要的过滤器参数
    company = filters.get("company")
    if not company:
        frappe.throw(_("Please select a Company"))

    period_start_date = filters.get("period_start_date")
    period_end_date = filters.get("period_end_date")
    if not (period_start_date and period_end_date):
        frappe.throw(_("Please set both Start Date and End Date"))

    fiscal_year = filters.get("fiscal_year")
    if not fiscal_year:
        frappe.throw(_("Please select a Fiscal Year"))

    # 获取比较选项
    compare_with_previous_year = filters.get("compare_with_previous_year", False)
    compare_with_budget = filters.get("compare_with_budget", False)
    budget = filters.get("budget")
    cost_center = filters.get("cost_center")  # 获取成本中心参数
    hide_chart = filters.get("hide_chart", False)

    # 预算比较验证
    if compare_with_budget and not budget:
        frappe.throw(_("Please select a Budget for comparison"))

    # 获取财务报表数据
    columns, data = get_financial_statements_cn(
        company=company,
        period_start_date=period_start_date,
        period_end_date=period_end_date,
        fiscal_year=fiscal_year,
        periodicity=filters.get("periodicity", "Monthly"),
        compare_with_previous_year=compare_with_previous_year,
        compare_with_budget=compare_with_budget,
        budget=budget,
        cost_center=cost_center  # 传递成本中心参数
    )

    # 根据勾选项决定是否生成图表数据
    chart_data = None
    if not hide_chart:
        # 计算图表所需参数
        total_income = 0.0
        total_expense = 0.0
        for d in data:
            if d.get("parent_account") == "Income":
                total_income += d.get("balance", 0)
            elif d.get("parent_account") == "Expenses":
                total_expense += d.get("balance", 0)
        
        # 计算净利润
        net_profit_loss = total_income - total_expense

        # 获取公司货币
        currency = frappe.get_cached_value("Company", company, "default_currency") or "CNY"

        # 生成图表数据
        chart_data = get_chart_data(
            filters, 
            columns, 
            data,
            total_expense,
            net_profit_loss,
            currency
        )

    return columns, data, None, chart_data